package com.umanji.user;

import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import net.sf.ehcache.util.counter.Counter;

import org.hsqldb.User;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.SessionScope;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.google.gson.Gson;
import com.umanji.security.domain.Authorities;
import com.umanji.security.domain.Users;
import com.umanji.security.service.AuthoritiesService;
import com.umanji.user.domain.Address;
import com.umanji.user.domain.Members;
import com.umanji.user.service.MemberService;
import com.umanji.security.service.UserService;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * Handles requests for the application welcome page.
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);

	private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @Autowired
    private AuthoritiesService securityAuthorityService;

    @Autowired
    private UserService securityUserService;

    @Autowired
    private MemberService umanjiUserService;

	/**
	 * Simply selects the welcome view to render by returning void and relying
	 * on the default request-to-view-translator.
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelMap login(ModelMap model) {
		logger.info("login page !");

		ModelMap mav = new ModelMap();
        mav.addObject("message", "Hello World!");
        return mav;
	}

	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public ModelMap updateUserForm(ModelMap model) {
		logger.info("update user form!");
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	
		Users umanji_user = new Users();
		umanji_user.setMember(new Members(umanji_user));

	    if (principal instanceof UserDetails) {
	    	
	    	logger.info(":::::::::::::::::::::::::::::::::::::::: found user ::::::::::::::::::");
	    	umanji_user = securityUserService.findByUsername(((UserDetails) principal).getUsername());
	    	
	    }
	    else{
	    	logger.info("::::::::::::::::::::::::::::::::::::::::not found user ::::::::::::::::::");
	    }
  
	   DateFormat formatter ; 
	   Date date ;    
	   formatter = new SimpleDateFormat("yyyy-MM-dd");
	   try {
		   logger.info("bbbbbbbbbbbbbbbbbbbbbbbbbbb:::"+umanji_user.getMember().getBirthDate());
		date = (Date)formatter.parse(umanji_user.getMember().getBirthDate().toString());
		   umanji_user.getMember().setBirthDate(date);
		   
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}    

        model.addObject("user", umanji_user.getMember());
        return model;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateUser(@ModelAttribute("user") Members umanji_member, BindingResult result, HttpServletRequest request) {
		logger.info("update user!");
		logger.info("birthday  ::" +umanji_member.getBirthDate() );

        for (ConstraintViolation<Members> constraint : validator.validate(umanji_member)) {
            result.rejectValue(constraint.getPropertyPath().toString(), "", constraint.getMessage());
        }
        if (result.hasErrors())
        	return "user/update";

		try {
			System.out.println("umanji_member.getFileData()  ::  "+umanji_member.getFileData());
			String rootPath = WebUtils.getRealPath(request.getSession().getServletContext(), "upload");
			umanji_member.setProfilePhoto( umanji_member.getSavedFileName(rootPath, umanji_member.getFileData(), "user") );
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        // umanji_member.setUser(umanji_member.getUser());
        // umanji_member.setVersion(new Long(1234234));
        
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        
        Users user = new Users();
        user.setMember(new Members(user));        
        user = securityUserService.findByUsername(((UserDetails) principal).getUsername());
        System.out.println("user.getMember().getProfilePhoto()  ::  "+user.getMember().getProfilePhoto());
        user.setPassword(umanji_member.getUser().getPassword());
        user.getMember().setNickName(umanji_member.getNickName());
        user.getMember().setProfilePhoto(umanji_member.getProfilePhoto());
        user.getMember().setEmailAddress(umanji_member.getEmailAddress());
        user.getMember().setPhoneNumber(umanji_member.getPhoneNumber());
        user.getMember().setAddress(umanji_member.getAddress());
        System.out.println("user.getMember().getProfilePhoto()  ::  "+user.getMember().getProfilePhoto());
        
        
        //securityUserService.merge(user);
        umanjiUserService.merge(user.getMember());
        //umanji_member.getUser().setEnabled(true);
		
		return "redirect:/umj/main/index";
	}

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelMap createUser(ModelMap model) {
		logger.info("register user form!");

		Users umanji_user = new Users();
		umanji_user.setMember(new Members(umanji_user));
		umanji_user.getMember().setAddress(new Address());
		

        model.addObject("member", umanji_user.getMember());
        return model;

	}
	
	@RequestMapping(value = "/userok/{name}", method = RequestMethod.GET)
	public @ResponseBody String okUser(@PathVariable String name, final HttpServletResponse response) {
		logger.info("okkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk :::  "+name);
		Object nameok = umanjiUserService.findname(name);
		System.out.println("nameeeeeeeeeeeeeeeeeeeeeeeeeeeeee :::  "+nameok);
		Gson gson = new Gson();
		String json = gson.toJson(nameok); 
		System.out.println("jsonnnnnnnnnnnnnnnnnnnnnnn:::"+json);

			return json;					
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@ModelAttribute("member") Members umanji_member, BindingResult result, HttpServletRequest request) {
		logger.info("register user!");
		logger.info("register email : " + umanji_member.getEmailAddress());
		logger.info("date~~~~~~~~~~~~~~ :"+umanji_member.getBirthDate());
		
		umanji_member.getUser().setEnabled(true);

		// umanji_member.getUser().getAuthority().setAuthority("ROLE_USER");
		// umanji_member.getUser().setAuthority(new Authorities(umanji_member.getUser(), "ROLE_USER"));

        for (ConstraintViolation<Members> constraint : validator.validate(umanji_member)) {
            result.rejectValue(constraint.getPropertyPath().toString(), "", constraint.getMessage());
        }
        if (result.hasErrors())
        	return "user/create";

        // umanji_member.setUser(umanji_member.getUser());
        // umanji_member.setVersion(new Long(1234234));
        // securityUserService.persist(umanji_member.getUser());
        //�ш린媛�臾몄젣��
		try {
			String rootPath = WebUtils.getRealPath(request.getSession().getServletContext(), "upload");
			umanji_member.setProfilePhoto( umanji_member.getSavedFileName(rootPath, umanji_member.getFileData(), "user") );
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        umanjiUserService.persist(umanji_member);
        logger.info("�ш린源뚯� �ㅻ젮��");
		securityAuthorityService.persist(new Authorities(umanji_member.getUser(), "ROLE_USER"));

        return "redirect:/umj/user/createEd";
	}
	
	@RequestMapping(value = "/createEd", method = RequestMethod.GET)
	public ModelMap createEd(ModelMap model) {
		Members umanji_member = new Members( new Users() );
		
		model.addObject("user", umanji_member);
		return model;		
	}

	@RequestMapping(value = "/delete/{userId}", method = RequestMethod.POST)
	public void delete(@PathVariable String userId, ModelMap model) {
		logger.info("delete user!");
	}
	
	@RequestMapping(value = "/findId", method = RequestMethod.GET)
	public ModelMap findId(ModelMap model) {
		Members umanji_member = new Members( new Users() );		
		model.addObject("user", umanji_member);
		return model;		
	}
	
	@RequestMapping(value = "/findPw", method = RequestMethod.GET)
	public ModelMap findPw(ModelMap model) {
		Members umanji_member = new Members( new Users() );
		model.addObject("user", umanji_member);
		return model;		
	}
	
	
	@RequestMapping(value = "/terms", method = RequestMethod.GET)
	public ModelMap terms(ModelMap model) {
		return model;		
	}
	
	@RequestMapping(value = "/needLog", method = RequestMethod.GET)
	public ModelAndView needLog(ModelMap model) {
		Members umanji_member = new Members( new Users() );
		ModelAndView mav = new ModelAndView();
		mav.setViewName("login");
		return mav;		
	}
	
	@RequestMapping(value = "/userfindId", method = RequestMethod.GET)
	public @ResponseBody String userFindId(@RequestParam("name") String name,@RequestParam("jumin1") Integer jumin1,@RequestParam("jumin2") Integer jumin2,final HttpServletResponse response) {
		String cou = umanjiUserService.userfindIdCount(name,jumin1,jumin2).toString();
		if(cou.equals("0")||cou=="0"){
			return "0";
		}else{
		Object nameok = umanjiUserService.userfindId(name,jumin1,jumin2);
		Gson gson = new Gson();
		String json = gson.toJson(nameok); 
		System.out.println("jsonnnnnnnnnnnnnnnnnnnnnnn:::"+json);
		return json;
		}
	}
	
	@RequestMapping(value = "/userfindPw", method = RequestMethod.GET)
	public @ResponseBody String userFindPw(@RequestParam("realname") String name,@RequestParam("jumin1") Integer jumin1,@RequestParam("jumin2") Integer jumin2,@RequestParam("userid") String userid,final HttpServletResponse response) {
		String count = umanjiUserService.userfindPwCount(name, jumin1, jumin2, userid).toString(); 
		if(count.equals("0")||count=="0"){
			return "0";
		}else{
		Object nameok = umanjiUserService.userfindPw(name,jumin1,jumin2,userid);	
		Gson gson = new Gson();
		String json = gson.toJson(nameok); 
		System.out.println("jsonnnnnnnnnnnnnnnnnnnnnnn:::"+json);
		return json;
		}
	}
	



}
